/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-7-10 下午1:32
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.activities;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.adapter.consulation.ConsulationCommentAdapter;
import com.example.dqhl.jdmetro.base.BaseActivity;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationComment;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationCommentCollet;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationDetailTop;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.Toastutils;
import com.example.dqhl.jdmetro.utils.recycleview.ConsulationRecycleViewLayoutManager;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:资讯详情
 * autour:guanluocang
 * date:17/7/10 13:33
 */
public class ConsulationDeatilActivity extends BaseActivity {

    @Bind(R.id.consulation_refresh_layout)
    TwinklingRefreshLayout consulation_refresh_layout;
    private Context context;
    private String info_id;
    @Bind(R.id.webview_detail)
    WebView webview_detail;

    //评论RecycleView
    @Bind(R.id.rv_consulation_comment)
    RecyclerView rv_consulation_comment;
    private ConsulationCommentAdapter consulationCommentAdapter;
    private List<ConsulationComment.DataBean> consulationComments = new ArrayList<>();
    @Bind(R.id.tv_noInfo)
    TextView tv_noInfo;
    //分享
//    @Bind(R.id.tv_weChat)
//    TextView tv_weChat;//微信好友
//    @Bind(R.id.tv_wc_friend)
//    TextView tv_wc_friend;//朋友圈
//    @Bind(R.id.tv_sina)
//    TextView tv_sina;//微博
    @Bind(R.id.tv_likeNum)
    TextView tv_likeNum;//点赞

    @Bind(R.id.tv_time)
    TextView tv_time;//时间
    @Bind(R.id.tv_number)
    TextView tv_number;//浏览量
    @Bind(R.id.tv_title)
    TextView tv_title;//标题


    //轮播图
    @Bind(R.id.sliderLayout)
    SliderLayout sliderLayout;
    @Bind(R.id.custom_indicator)
    PagerIndicator custom_indicator;
    List<String> bannerList = new ArrayList<>();

    @Bind(R.id.et_speakContent)
    EditText et_speakContent;//评论内容
    @Bind(R.id.tv_sendMsg)
    TextView tv_sendMsg;//发送按钮

    private int page = 1;//分页
    private int isCollect = 0;//是否收藏

    @Override
    public void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_consulation_deatil);
        initTitleBar("资讯详情");
        setRightTextVisibility(View.GONE);
        context = this;
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void initData() {
        ConsulationRecycleViewLayoutManager layoutManager = new ConsulationRecycleViewLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_consulation_comment.setLayoutManager(layoutManager);
        rv_consulation_comment.setItemAnimator(new DefaultItemAnimator());
        rv_consulation_comment.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rv_consulation_comment.setNestedScrollingEnabled(false);
//        rv_consulation_comment.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
//        rv_consulation_comment.setLoadingMoreProgressStyle(ProgressStyle.Pacman);
//        rv_consulation_comment.setArrowImageView(R.drawable.iconfont_downgrey);
        info_id = getIntent().getStringExtra("info_id");
        ProgressLayout headerView = new ProgressLayout(this);
        consulation_refresh_layout.setHeaderView(headerView);
        consulation_refresh_layout.setOverScrollRefreshShow(false);
        if (user != null) {
            getConsulationTitle();
            getContent();
            getCommentList(page);
            getCollectNum(0);
        } else {
            Toastutils.show("请先登录");
        }
    }

    @Override
    public void initListener() {
        tv_sendMsg.setOnClickListener(this);
        tv_likeNum.setOnClickListener(this);

        consulation_refresh_layout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                page = 1;
                getCommentList(page);
                refreshLayout.finishRefreshing();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                page++;
                doMoreCommentList(page);
                refreshLayout.finishLoadmore();
            }
        });
    }


    /**
     * 资讯内容
     */
    public void getContent() {
        RequestParams params = new RequestParams(Config.consulation_detail);
        params.addBodyParameter("info_id", info_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    Dlog.e(result);
                    String address = JsonUtils.getInfo(data, "address");
                    //设置此属性，可任意比例缩放
//        webView.getSettings().setUseWideViewPort(true);
//        webView.getSettings().setLoadWithOverviewMode(true);
                    // 设置自动加载图片
                    webview_detail.getSettings().setLoadsImagesAutomatically(true);
                    //支持缩放
                    webview_detail.getSettings().setBuiltInZoomControls(false);
                    //设置是否支持变焦
                    webview_detail.getSettings().setSupportZoom(true);
                    //  这是webview保存表单数据
                    webview_detail.getSettings().setSaveFormData(false);
                    //自适应屏幕
//        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webView.getSettings().setLoadWithOverviewMode(true);
                    //启用支持javascript
                    webview_detail.getSettings().setJavaScriptEnabled(true);
                    // 优先使用缓存
                    webview_detail.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //  不使用缓存 只从网络获取数据
//                    WebSettings webSettings = webview_detail.getSettings();
//                    webSettings.setUseWideViewPort(true); //设置webview推荐使用的窗口
//                    webSettings.setLoadWithOverviewMode(true); //设置webview加载的页面的模式
//                    webSettings.setUseWideViewPort(true);
                    webview_detail.loadUrl(address);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 资讯title
     */
    public void getConsulationTitle() {
        RequestParams params = new RequestParams(Config.consulation_detail_title);
        params.addBodyParameter("info_id", info_id);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("资讯详情title" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    ConsulationDetailTop detailTop = new Gson().fromJson(result, ConsulationDetailTop.class);
                    bannerList = detailTop.getData().getPic_all();
                    tv_time.setText(detailTop.getData().getRelease_time());
                    tv_title.setText(detailTop.getData().getTitle_a());
                    tv_number.setText(detailTop.getData().getPage_view() + "");
                    for (int i = 0; i < bannerList.size(); i++) {
                        //新建三个展示View，并且添加到SliderLayout
                        TextSliderView tsv = new TextSliderView(ConsulationDeatilActivity.this);
                        tsv.image(Config.pic_base_url + bannerList.get(i));

                        sliderLayout.addSlider(tsv);
                    }
                    //对SliderLayout进行一些自定义的配置
                    sliderLayout.setCustomAnimation(new DescriptionAnimation());
                    //设置滑动的动画
                    sliderLayout.setPresetTransformer(SliderLayout.Transformer.Tablet);
                    sliderLayout.setDuration(3000);
                    //      sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
                    sliderLayout.setCustomIndicator(custom_indicator);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取收藏数量
     */
    private void getCollectNum(final int is_collect) {
        RequestParams params = new RequestParams(Config.consulation_collect_comment);
        params.addBodyParameter("info_id", info_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("state", is_collect + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("收藏数量" + result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    ConsulationCommentCollet consulationCommentCollet = JSON.parseObject(data, ConsulationCommentCollet.class);
                    tv_likeNum.setText(consulationCommentCollet.getCount_collect() + "");
                    // 收藏状态：0-未收藏，1-已收藏
                    Drawable drawable_pressed = getResources().getDrawable(R.drawable.ic_like_pressed);
                    Drawable drawable = getResources().getDrawable(R.drawable.ic_like);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    drawable_pressed.setBounds(0, 0, drawable_pressed.getMinimumWidth(), drawable_pressed.getMinimumHeight());
                    if (consulationCommentCollet.getIs_collect() == 0) {
                        isCollect = 1;
                        tv_likeNum.setCompoundDrawables(null, drawable, null, null);
                    } else {
                        isCollect = 2;
                        tv_likeNum.setCompoundDrawables(null, drawable_pressed, null, null);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sendMsg:
                doSendMsg();
                break;
            //收藏
            case R.id.tv_likeNum:
                getCollectNum(isCollect);
                break;
        }
    }

    //加载更多
    public void doMoreCommentList(int pages) {
        Dlog.e("pagpagpagpagpagpagpagpage" + page);
        RequestParams params = new RequestParams(Config.consulation_detail_comment);
        params.addBodyParameter("page", pages + "");
        params.addBodyParameter("info_id", info_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    ConsulationComment consulationComment = new Gson().fromJson(result, ConsulationComment.class);
                    consulationComments.addAll(consulationComment.getData());
                    rv_consulation_comment.setAdapter(consulationCommentAdapter);
                    consulationCommentAdapter.notifyDataSetChanged();
                } else {
                    Toastutils.show("暂无更多数据");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 发送信息
     */
    private void doSendMsg() {
        String msg = et_speakContent.getText().toString().trim();
        if (!TextUtils.isEmpty(msg)) {
            RequestParams params = new RequestParams(Config.consulation_add_comment);
            params.addBodyParameter("info_id", info_id);
            params.addBodyParameter("id_auth", user.getId_auth());
            params.addBodyParameter("content", msg);
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("评论成功" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        et_speakContent.setText("");
                        InputMethodManager imm1 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm1.hideSoftInputFromWindow(et_speakContent.getWindowToken(), 0);//从控件所在的窗口中隐藏
                        page = 1;
                        getCommentList(page);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
        } else {
            Toastutils.show("请输入内容");
        }
    }

    /**
     * 获取评论列表
     */

    public void getCommentList(int pages) {
        Dlog.e("pagpagpagpagpagpagpagpage" + page);
        RequestParams params = new RequestParams(Config.consulation_detail_comment);
        params.addBodyParameter("page", pages + "");
        params.addBodyParameter("info_id", info_id);
        params.addBodyParameter("id_auth", user.getId_auth());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getData(result);
                String errMsg = JsonUtils.getErrMsg(result);
                if (errCode == 200) {
                    ConsulationComment consulationComment = new Gson().fromJson(result, ConsulationComment.class);
                    consulationComments = consulationComment.getData();
                    if (consulationComments.size() == 0 || consulationComments == null) {
                        tv_noInfo.setVisibility(View.VISIBLE);
                        rv_consulation_comment.setVisibility(View.GONE);
                    } else {
                        tv_noInfo.setVisibility(View.GONE);
                        rv_consulation_comment.setVisibility(View.VISIBLE);
                        consulationCommentAdapter = new ConsulationCommentAdapter(context, consulationComments, new ConsulationCommentAdapter.OnFabulousListener() {
                            @Override
                            public void onFabulous(int position) {
                                doFabulous(position);
                            }
                        }, new ConsulationCommentAdapter.OnDeleteListener() {
                            @Override
                            public void onDelete(int position) {
                                doDelete(position);
                            }
                        });
                        rv_consulation_comment.setAdapter(consulationCommentAdapter);
                        consulationCommentAdapter.notifyDataSetChanged();
//                    consulationCommentAdapter.refresh_newHots(consulationComment.getData());
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 点赞
     */

    public void doFabulous(int position) {
        showLoadingBar("");
        final RequestParams params = new RequestParams(Config.consulation_fabulous_comment);
        params.addBodyParameter("id_auth", user.getId_auth());
        params.addBodyParameter("comment_id", consulationComments.get(position).getComment_id());
        // 赞的状态：0-未赞，1-已赞
        if (consulationComments.get(position).getIs_praise() == 1) {
            params.addBodyParameter("state", 2 + "");
        } else {
            params.addBodyParameter("state", 1 + "");
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e("点赞" + result);
                int errCode = JsonUtils.getErrCode(result);
                if (errCode == 200) {
                    getCommentList(page);
                    consulationCommentAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideLoadingBar();
            }
        });
    }

    /**
     * 删除
     */
    public void doDelete(int position) {
        Dlog.e("GG" + consulationComments.get(position).getComment_user());
        Dlog.e("GG" + user.getId_auth());
        if (consulationComments.get(position).getComment_user().equals(user.getId_auth())) {
            showLoadingBar("");
            RequestParams params = new RequestParams(Config.consulation_delete_comment);
            params.addBodyParameter("comment_id", consulationComments.get(position).getComment_id());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Dlog.e("删除" + result);
                    int errCode = JsonUtils.getErrCode(result);
                    if (errCode == 200) {
                        getCommentList(page);
                        consulationCommentAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideLoadingBar();
                }
            });
        } else {
            Toastutils.show("只可删除私有评论");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }
}
